﻿#include "loginwidget.h"
#include "ui_loginwidget.h"
#include <QDebug>
#include <QMessageBox>
#include <QSqlQuery>
#include <QSqlError>
#include <QCryptographicHash>

LoginWidget::LoginWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::LoginWidget)
{
    ui->setupUi(this);
    initDatabase();
    setWindowTitle("登录 - myMusic");
    setFixedSize(400, 300);
}

LoginWidget::~LoginWidget()
{
    delete ui;
    if(db.isOpen()) {
        db.close();
    }
}

void LoginWidget::initDatabase()
{
    // 初始化数据库连接
    db = QSqlDatabase::addDatabase("QSQLITE", "loginConnection");
    db.setDatabaseName("myMusic.db");

    if (!db.open()) {
        QMessageBox::critical(this, "错误", "无法打开数据库");
        return;
    }

    // 创建用户表
    QSqlQuery query(db);
    query.exec("CREATE TABLE IF NOT EXISTS users ("
              "id INTEGER PRIMARY KEY AUTOINCREMENT,"
              "username VARCHAR(50) UNIQUE NOT NULL,"
              "password VARCHAR(64) NOT NULL,"
              "created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP"
              ")");

    // 创建用户-歌曲关系表
    query.exec("CREATE TABLE IF NOT EXISTS user_music_info ("
              "id INTEGER PRIMARY KEY AUTOINCREMENT,"
              "username VARCHAR(50) NOT NULL,"
              "music_id VARCHAR(200) NOT NULL,"
              "is_like INTEGER DEFAULT 0,"
              "is_history INTEGER DEFAULT 0,"
              "last_play_time TIMESTAMP,"
              "UNIQUE(username, music_id),"
              "FOREIGN KEY(username) REFERENCES users(username),"
              "FOREIGN KEY(music_id) REFERENCES musicInfo(musicId)"
              ")");
}

QString hashPassword(const QString& password)
{
    QByteArray hash = QCryptographicHash::hash(
        password.toUtf8(),
        QCryptographicHash::Sha256
    );
    return hash.toHex();
}

bool LoginWidget::verifyUser(const QString& username, const QString& password)
{
    QSqlQuery query(db);
    query.prepare("SELECT password FROM users WHERE username = ?");
    query.addBindValue(username);

    if (!query.exec() || !query.next()) {
        return false;
    }

    QString storedHash = query.value(0).toString();
    QString inputHash = hashPassword(password);

    return storedHash == inputHash;
}

bool LoginWidget::registerUser(const QString& username, const QString& password)
{
    QSqlQuery query(db);
    query.prepare("INSERT INTO users (username, password) VALUES (?, ?)");
    query.addBindValue(username);
    query.addBindValue(hashPassword(password));

    return query.exec();
}

void LoginWidget::on_loginButton_clicked()
{
    QString username = ui->usernameEdit->text();
    QString password = ui->passwordEdit->text();

    if (username.isEmpty() || password.isEmpty()) {
        QMessageBox::warning(this, "警告", "用户名和密码不能为空");
        return;
    }

    if (verifyUser(username, password)) {
        emit loginSuccess(username);
        hide();
    } else {
        QMessageBox::warning(this, "错误", "用户名或密码错误");
    }
}

void LoginWidget::on_registerButton_clicked()
{
    QString username = ui->usernameEdit->text();
    QString password = ui->passwordEdit->text();

    if (username.isEmpty() || password.isEmpty()) {
        QMessageBox::warning(this, "警告", "用户名和密码不能为空");
        return;
    }

    if (registerUser(username, password)) {
        QMessageBox::information(this, "成功", "注册成功，请登录");
    } else {
        QMessageBox::warning(this, "错误", "注册失败，用户名可能已存在");
    }
}
